package com.zzf.broadcasttest

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.annotation.RequiresApi
import kotlinx.android.synthetic.main.activity_main.*
import java.lang.StringBuilder
import java.time.LocalDate

class MainActivity : AppCompatActivity() {

    lateinit var timeChangeReciiver: TimeChangeReciiver

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val intentFilter = IntentFilter()
        intentFilter.addAction("android.intent.action.TIME_TICK")
        timeChangeReciiver = TimeChangeReciiver()
        registerReceiver(timeChangeReciiver,intentFilter)

        button.setOnClickListener {
            val intent = Intent("com.zzf.broadcasttest.MY_BROADCAST")
            intent.setPackage(packageName)
            sendBroadcast(intent)
        }

        val result1 = num1AndNum2(100,200,::plus)
        val result2 = num1AndNum2(100,200,::minus)
        val result3 = num1AndNum2(100,200) {n1,n2 ->
            n1 * n2
        }

        println("result1 is $result1")
        println("result2 is $result2")
        println("result3 is $result3")

        val list = listOf("Apple","Banana","Orange")
        val result = StringBuilder().build {
            append("start eating fruits.\n")
            for (fruit in list){
                append(fruit).append("\n")
            }
            append("ate all fruits.")
        }
        println(result.toString())
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(timeChangeReciiver)
    }

    inner class TimeChangeReciiver:BroadcastReceiver(){
        @RequiresApi(Build.VERSION_CODES.O)
        override fun onReceive(context: Context?, intent: Intent?) {
            textView.setText(LocalDate.now().toString())
            Toast.makeText(context, "Time has changed", Toast.LENGTH_SHORT).show()
        }
    }
}